package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Log4j2
@Controller
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

//    @Resource
//    private DiscoveryClient discoveryClient;

    @ResponseBody
    @PostMapping(value = "/payments")
    public CommonResult addPayment(@RequestBody Payment payment){
        int result = paymentService.addPayment(payment);
        log.info("************插入结果*************"+result);
        if (result>0){
            return new CommonResult(200,"插入成功"+serverPort,result);
        }else {
            return new CommonResult(444,"写入数据库失败"+serverPort,null);
        }
    }

    @ResponseBody
    @GetMapping(value = "/payment/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") long id){
        Payment payment = paymentService.getPaymentById(id);
        log.info("*********查询结果********"+serverPort+payment);

        if (payment==null){
            return new CommonResult(444,"查询失败"+serverPort,null);
        }else {
            return new CommonResult(200,"查询成功"+serverPort,payment);
        }
    }
//
//    @ResponseBody
//    @GetMapping(value = "/payment/discovery")
//    public Object discovery(){
//
//        List<String> services = discoveryClient.getServices();
//        for (String service : services) {
//          log.info("******service:"+service);
//        }
//
//        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
//        for (ServiceInstance instance : instances) {
//            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
//        }
//
//        return this.discoveryClient;
//
//    }

    @ResponseBody
    @RequestMapping(value = "/payment/zk")
    public String paymentZk(){
        return "Spring cloud whit zookeeper:  "+serverPort+ UUID.randomUUID().toString();
    }

}
